//index.js
//获取应用实例

var $http = require('../../utils/api/index.js')
var root = require('../../utils/http.js')
var $dtdetailhttp = require('../../utils/api/dtdetail.js')
const $ = require('../../utils/js.js')
const app = getApp()
var img_gy_src = $.img_gy_src;
var image_gy_src = $.image_gy_src;
Page({
  data: {
    img_gy_src: img_gy_src,
    image_gy_src: image_gy_src,
    imgurl: root.imgurl,
    bdimg: image_gy_src + '/bj.png',
    tonglists: [{
      text: '帖子',
      num: "",
      img: image_gy_src + '/tiezi.png'
    }, {
      text: '人气',
      num: "",
      img: image_gy_src + '/renqi.png'
    }, {
      text: '成员',
      num: "",
      img: image_gy_src + '/chengyuan.png'
    }], //统计
    fenleilist: [],
    currentSwiper: 0,
    tabtop: 0,
    dttabHeight: 0,
    dtlists: [{
      name: '推荐',
      ename: 'is_recommend'
    }, {
      name: '关注',
      ename: 'care'
    }, {
      name: '身边',
      ename: 'near'
    }, {
      name: '热帖',
      ename: 'hot'
    }, {
      name: '名片榜',
      ename: 'mpbang'
    }],
    currentDt: 'is_recommend',
    page: 1,
    latitude: 0,
    longitude: 0,
    dongtailists: [],
    isgzlist: false,
    loadshow: false,
    ding_wei: false,

    debug_hide: true,
  },
  //选择动态
  xzDt(e) {
    var ename = e.currentTarget.dataset.ename
    this.setData({
      currentDt: ename,
      page: 1
    })
    if (ename == 'mpbang') {
      $.open('/pages/index/name_card_list/name_card_list');
    } else {
      this.dongtaixuanren(this.data.page, this.data.longitude, this.data.latitude)
    }
  },
  // 跳转到名片详情
  go_name_card(e) {
    var user_id = $.data(e, "user_id");
    $.open('/pages/index/name_card_xq/name_card_xq?back=1&id=' + user_id);
  },
  // 点赞
  dianzan(e) {
    var index = e.currentTarget.dataset.idx;
    var dtid = e.currentTarget.dataset.id;
    var islike = e.currentTarget.dataset.islike;
    const dianzanafter = 'dongtailists[' + index + '].is_like'
    if (islike == 0) {
      // 点赞
      $dtdetailhttp.like(dtid, 1).then((res) => {
        this.setData({
          [dianzanafter]: 1,
        })
      })
    } else {
      // 取消
      $dtdetailhttp.like(dtid, 2).then((res) => {
        this.setData({
          [dianzanafter]: 0,
        })
      })
    }
  },
  swiperChange: function(e) {
    this.setData({
      currentSwiper: e.detail.current
    })
  },
  queryMultipleNodes: function() {
    var that = this
    var query = wx.createSelectorQuery()
    query.select('.dt_tab').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function(res) {

      res[0].top // #the-id节点的上边界坐标
      res[1].scrollTop // 显示区域的竖直滚动位置
      that.setData({
        tabtop: res[0].top,
        dttabHeight: res[0].height
      })
    })
  },
  // 跳转到小程序码页面
  go_xcxma_fun() {
    wx.navigateTo({
      url: '/pages/index/xcxma/xcxma'
    })
  },
  onReady: function() {
    this.queryMultipleNodes()

  },
  onLoad: function(options) {
    // 获取数据
    wx.request({
      url: "https://www.yifale.com/api/set",
      header: {
        'Accept': 'application/json',
        'content-type': 'application/x-www-form-urlencoded',
      },
      success: (res) => {
        var text_data = res.data;
        $.title(text_data[0]);
      },
    })
    // 获取数据
    wx.request({
      url: "https://www.yifale.com/api/set/debug",
      header: {
        'Accept': 'application/json',
        'content-type': 'application/x-www-form-urlencoded',
      },
      success: (res) => {
        var debug_hide = res.data;
        this.setData({
          debug_hide: debug_hide
        })

        if (debug_hide) {
          var dtlists = this.data.dtlists;
          var tonglists = this.data.tonglists;
          dtlists.splice(3, 1);
          tonglists.splice(0, 1);
          this.setData({
            dtlists: dtlists,
            tonglists: tonglists
          })
        }
      },
    })

    // 获取广告
    this.get_guang_gao();

    $.ding_wei((data) => {
      console.log(data)
      this.setData({
        ding_wei: data.root
      })

    })
    // 首页统计数据、图片
    $http.statistic().then((res) => {

      var tonglists = this.data.tonglists.map((item, index) => {
        if (index == 0) {
          item.num = res.data.data.tiezi
        } else if (index == 1) {
          item.num = res.data.data.renqi
        } else {
          item.num = res.data.data.chengyuan
        }
        return item
      })
      this.setData({
        tonglists: tonglists,
        bdimg: res.data.data.image
      })
    })

    // 分类
    $http.category('circle').then((res) => {

      if (res.data.code == 1) {
        var arr = new Array(Math.ceil(res.data.data.length / 10))

        this.setData({
          fenleilist: res.data.data,
          flpage: arr
        })
      }

    })

    //公告
    $http.notices().then((res) => {
      console.log(res.data.data)
      if (res.data.code == 1) {
        this.setData({
          gginfo: res.data.data
        })
      }

    })
    // 调用滚动悬停函数
    this.scroll_xuan_ting_fun();
    //获取地理位置
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        var latitude = res.latitude
        var longitude = res.longitude
        this.setData({
          latitude: latitude,
          longitude: longitude,
        })
        //动态推荐列表
        this.dongtaixuanren(this.data.page, this.data.longitude, this.data.latitude)
      }.bind(this)
    })
    // app.editTabBar();
    var imgdots = new Array(Math.ceil(this.data.fenleilist.length / 10))

    this.setData({
      imgdots: imgdots
    })


  },
  fldetail(e) {
    wx.navigateTo({
      url: 'hylb/hylb?catid=' + e.currentTarget.dataset.catid + "&title=" + e.currentTarget.dataset.title,
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

    this.setData({
      page: 1
    })
    //动态推荐列表
    this.dongtaixuanren(this.data.page, this.data.longitude, this.data.latitude)
  },
  // 获取广告
  get_guang_gao() {
    $.ajax_get({
      url: "/common/ad",
      data: {
        pid: 1
      },
      success: (res) => {
        var data = res.data;
        console.log("广告数据", data);
      },
    });
  },
  dongtaixuanren(page, longitude, latitude) {
    $http.list(page, this.data.currentDt, longitude, latitude).then((res) => {
      console.log(res.data.data)
      if (res.data.code == 1) {
        if (this.data.currentDt == 'care') {
          if (res.data.data.no_care == 1) {
            $http.circle_users(page).then((res1) => {
              this.setData({
                isgzlist: true,
                guanzhulists: res1.data.data,
                loadshow: false
              })
            })

          } else {
            this.setData({
              isgzlist: false,
              dongtailists: res.data.data,
              loadshow: false
            })
          }
        } else {
          this.setData({
            isgzlist: false,
            dongtailists: res.data.data,
            loadshow: false
          })
        }
      }
    })
  },
  // 搜索
  search() {
    wx.navigateTo({
      url: 'search/search'
    })
  },
  // 发布
  fabu() {
    if (getApp().globalData.token) {
      wx.navigateTo({
        url: 'fabu/fabu'
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000,
        success: function() {
          wx.navigateTo({
            url: '/pages/login/login'
          })
        }
      })
    }
  },
  dtdetail(e) {
    wx.navigateTo({
      url: 'dtdetail/dtdetail?id=' + e.currentTarget.dataset.id
    })
  },
  gonggao() {
    wx.navigateTo({
      url: 'gonggao/gonggao'
    })
  },

  // 关注
  guanzhu(e) {
    var id = e.currentTarget.dataset.id
    var is_care = e.currentTarget.dataset.is_care
    var idx = e.currentTarget.dataset.index
    console.log(idx)
    $http.care(id, is_care == 0 ? 1 : 2).then((res) => {
      console.log(res)
      wx.showToast({
        title: res.data.msg,
        icon: 'none'
      })
      if (res.data.code == 1) {
        var a = 'guanzhulists[' + idx + '].is_care'
        this.setData({
          [a]: is_care == 0 ? 1 : 0
        })
      }
    })
  },
  // 进入图片预览
  yu_lan_fun(e) {
    var img = $.data(e, "img");
    var imgs = $.data(e, "imgs");
    $.yu_lan(img, imgs)
  },
  // 滚动悬停函数
  scroll_xuan_ting_fun() {
    // 屏幕显示区域与标注线相交或相离时触发
    wx.createIntersectionObserver().relativeToViewport({
      top: 0
    }).observe("#biao_zhu", (res) => {
      // 打印相交或者相离时的数据
      // console.log(res);
      // 如果是相离，并且是从顶部相离，开启悬浮
      if (res.intersectionRect.height == 0 && res.boundingClientRect.bottom <= 0) {
        this.setData({
          isfixed: true,
        })
      } else {
        this.setData({
          isfixed: false,
        })
      }
    })
  },
  // 无用函数，防止冒泡
  no_fun() {

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    this.setData({
      page: ++this.data.page,
      loadshow: true
    })
    // setTimeout(() => {
    //   this.setData({
    //     loadshow: false
    //   })
    // }, 1000)
    $http.list(this.data.page, this.data.currentDt, this.data.longitude, this.data.latitude).then((res) => {
      if (res.data.code == 1) {
        if (this.data.currentDt == 'care') {
          if (res.data.data.no_care == 1) {
            $http.circle_users(this.data.page).then((res1) => {
              this.data.guanzhulists.push(...res1.data.data)
              this.setData({
                isgzlist: true,
                guanzhulists: this.data.guanzhulists,
                loadshow: false
              })
            })
          } else {
            this.setData({
              loadshow: false
            })
          }
        } else {
          setTimeout(() => {
            this.data.dongtailists.push(...res.data.data)
            this.setData({
              isgzlist: false,
              dongtailists: this.data.dongtailists
            })
            this.setData({
              loadshow: false
            })
          }, 1000)
        }
      }
    })
  },
  //前往聊天
  liao_tian(e) {
    $.deng_lu(function() {
      var receive_id = $.data(e, "receive_id");
      var title = $.data(e, "title");
      $.open("/pages/my/liao_tian_content/liao_tian_content?user_id=" + getApp().globalData.userinfo.id + '&receive_id=' + receive_id + "&title=" + title);
    })
  },
  // 滚动到顶部
  go_top() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },
  // 转发
  onShareAppMessage: function(e) {
    if (e.from == "button") {
      var item = e.target.dataset.item;
      return {
        title: item.content,
        path: "/pages/index/dtdetail/dtdetail?notice=1&id=" + item.id
      }
    } else {
      return {
        title: "您的好友邀请你逛逛易发了网信息发布查询大平台",
      }
    }
  }
})